<template>
  <Page title="学习资料">
    <template v-slot:navBarCustom>
      <div class=""></div>
    </template>
    <template v-slot:content>
      <div class="w-full h-full p-20px box-border">
        <div class="container w-full h-full bg-white flex flex-col p-20px box-border">
          <div class="header" style="font-size: 0">
            <TagGroup
              :data="subjects"
              title="科目"
              title-style="width:0.72rem"
              :id="subjectId"
              @on-click="clickSubject"
            ></TagGroup>
            <TagGroup
              :data="folderTypeList"
              title="资料分类"
              :id="folderTypeId"
              @on-click="clickSubject"
            ></TagGroup>
            <TagGroup
              :data="readStatusList"
              title="查阅情况"
              :id="readStatusId"
              @on-click="clickSubject"
            ></TagGroup>
            <el-input
              v-model="fileName"
              placeholder="搜索文件名"
              type="text"
              size="large "
              suffix-icon="el-icon-search"
              class="mb-20px"
              style="width: 5.7rem"
            />
          </div>
          <scroll-view class="flex-1 overflow-scroll" @scrolltolower="loadMore">
            <div
              v-for="(item, index) in learningList"
              :key="index"
              class="learning-list"
              style="font-size: 0"
            >
              <p class="font-medium mb-10px" style="font-size: 0.2rem">
                {{ item.shareTime }}
              </p>
              <div class="grid w-full">
                <CardItem
                  v-for="i in item.studyDataRespList"
                  :key="i.id"
                  ref="learning"
                  :id="i.id"
                  :item="i"
                  :audioUrl="i.fileUrl"
                  @on-click="clickFile"
                  @on-play="onPlay($event, i)"
                  @on-play-audio="onPlayAudio"
                >
                </CardItem>
              </div>
            </div>
            <load-more
              cssStyle="padding-bottom:0.1rem"
              :loading="loading"
              :has-more="hasMore"
              @click="loadMore"
            />
          </scroll-view>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Vue from 'vue'
import Page from '@/components/page/index'
import TagGroup from '../learning/components/TagGroup.vue'
import ScrollView from '@/components/scroll-view'
import CardItem from '../learning/components/CardItem.vue'
import LoadMore from '@/components/load-more'
import {
  getDictList,
  getLearningList,
  getFileUrl,
  setReadStatus,
  getStudentCoursesList
} from '@/api/learning/index.js'
import { getTenantId } from '../../utils/auth.js'
import { determineType } from './fileType.js'
import { MODULE_ID } from '@/store/modules/module-use'

export default {
  components: {
    Page,
    TagGroup,
    ScrollView,
    CardItem,
    LoadMore
  },
  beforeRouteLeave(to, from, next) {
    for (let key in this.audioContexts) {
      const { context, item } = this.audioContexts[key]
      context.context.pause()
      context.status = false
      context.$emit('on-click', { readStatus: 2, item: item })
    }

    next()
  },
  data() {
    return {
      searchInput: '',
      subjects: [],
      subjectId: '',
      folderTypeList: [],
      folderTypeId: '0',
      readStatusList: [],
      readStatusId: '-1',
      learningList: [],
      fileName: '',
      pageParm: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      loading: false,
      hasMore: true,
      productPlay: false,
      scrollTimer: null,
      audioContexts: {}
    }
  },
  watch: {
    fileName(n) {
      if (!n) return

      this.debounce(() => {
        // 执行搜索操作
        this.fileName = n
        this.search()
      }, 500)
    }
  },
  async created() {
    const id = await getTenantId()
    const res = await getFileUrl({ id: id })
    console.log(res)
    this.$store.state.learning.minioConfig = res.data
  },
  // async onShow() {
  // 	await this.getData({
  // 		fileType: this.folderTypeId == '0' ? '' : this.folderTypeId,
  // 		readStatus: this.readStatusId == '-1' ? '' : this.readStatusId,
  // 		subject: this.subjectId,
  // 		...this.pageParm
  // 	});
  // },
  async mounted() {
    const res = await getStudentCoursesList()

    // 如果没有开通的科目，弹出弹窗
    if (res.data.length === 0) {
      this.$popup.show({
        type: 'alert',
        success: (popup) => {
          popup.$on('confirm', () => {
            this.$popup.hide('alert')
            this.$router.back()
          })
          popup.setData({
            content: '没有已开通的科目'
          })
        }
      })
      return
    }

    this.subjects = res.data
    this.subjectId = res.data[0].value

    // 初始化模块使用记录
    this.$store.commit('setCurrentModuleUse', {
      vm: this._self,
      type: MODULE_ID.LEARNING,
      subjectId: this.subjectId
    })

    const r = await getDictList()
    const data = r.data
    this.folderTypeList.push({
      dictType: 'data_file_type',
      label: '全部',
      value: '0'
    })
    this.readStatusList.push({
      dictType: 'means_readStatus',
      value: '-1',
      label: '全部'
    })
    data.forEach((item) => {
      if (item.dictType == 'data_file_type') {
        if (item.value !== '1') {
          this.folderTypeList.push(item)
        }
      }
      if (item.dictType == 'means_readStatus') {
        this.readStatusList.push(item)
      }
    })
    await this.getData({
      fileType: this.folderTypeId == '0' ? '' : this.folderTypeId,
      readStatus: this.readStatusId == '-1' ? '' : this.readStatusId,
      subject: this.subjectId,
      ...this.pageParm
    })
    await this.$nextTick()
  },
  methods: {
    onScroll() {
      clearTimeout(this.scrollTimer)
      this.scrollTimer = setTimeout(() => {
        const c = this.$refs.learning
        c.forEach((item) => {
          if (item._props.item.fileType == 5) {
            let audioId = item._props.id
            item.$u.getRect('.audio' + audioId).then((rect) => {
              if (rect.top <= 0) {
                //第一种情况 向上滑动 滑过顶部到不可见区域
                if (item._data.status == false) {
                  //如果是播放状态
                  if (item.getData()) {
                    item._data.status = true
                  }
                } else {
                  item.start(item._props.item)
                  item._data.status = false
                }
              } else if (rect.top > uni.getSystemInfoSync().windowHeight) {
                if (item._data.status == false) {
                  //如果是播放状态
                  if (item.getData()) {
                    item._data.status = true
                  }
                } else {
                  item.start(item._props.item)
                }
              } else {
                //可见区域
                console.log('可见区域可见区域')
                item._data.status = false
              }
            })
          }
        })
      }, 300)
    },
    // 点击资料
    async clickFile(item) {
      if (!item.item.hasOwnProperty('fileType')) return

      const { fileType, isSystemFile } = item.item

      const url = this.$store.state.learning.minioConfig.fileServerUrlApp
      const bucket =
        isSystemFile == 0 ? 'snd-ai-assistant' : this.$store.state.learning.minioConfig.bucket
      const fileUrl = item.item.fileUrl

      switch (fileType) {
        case 2:
          // photo
          if (item.item.coverUrl) {
            const file = item.item
            const currentSrc =
              this.$store.state.learning.minioConfig.fileServerUrlApp +
              '/' +
              this.$store.state.learning.minioConfig.bucket +
              file.fileUrl
            let ElImageViewer = Vue.extend({
              data: function () {
                return {
                  elImageViewerVisible: true,
                  elImageViewerList: [currentSrc]
                }
              },
              template:
                '<el-image-viewer v-if="elImageViewerVisible" :on-close="() => {elImageViewerVisible = false}" :url-list="elImageViewerList" />'
            })
            let component = new ElImageViewer().$mount()
            document.body.appendChild(component.$el)
          }

          this.$nextTick(async () => {
            await setReadStatus(item.item.id, 1, new Date())
            const mask = document.getElementsByClassName('el-image-viewer__mask')[0]
            const closeBtn = document.getElementsByClassName(
              'el-image-viewer__btn el-image-viewer__close'
            )[0]

            // 监听图片关闭事件
            mask.onclick = async () => {
              await setReadStatus(item.item.id, 2, new Date())
              item.item.readStatus = 1
            }
            closeBtn.onclick = async () => {
              await setReadStatus(item.item.id, 2, new Date())
              item.item.readStatus = 1
            }
          })
          break
        case 3:
          // video
          if (item.readStatus == 1) {
            await setReadStatus(item.item.id, 1, new Date())
          } else {
            await setReadStatus(item.item.id, 2, new Date())
            item.item.readStatus = 1
          }
          break
        case 5:
          // audio
          if (item.readStatus == 1) {
            await setReadStatus(item.item.id, 1, new Date())
            item.item.readStatus = 1
          } else {
            await setReadStatus(item.item.id, 2, new Date())
          }
          break
        default:
          // other
          const fn = item.item.fileName + fileUrl.slice(fileUrl.lastIndexOf('.')) //文件名带后缀
          const callback = async (fileName) => {
            await setReadStatus(item.item.id, 2, new Date())
            item.item.readStatus = 1
          }
          const callBackName = 'fuc'
          window.android_call[callBackName] = callback.bind(this)
          android.openFile(`${url}/${bucket}${fileUrl}`, fn, callBackName)
          setReadStatus(item.item.id, 1, new Date())
          break
      }
    },
    debounce(fn, delay) {
      //防抖节流
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        fn()
      }, delay)
    },
    async getData(obj) {
      if (this.loading) return

      this.loading = true

      const {
        data: { list, total }
      } = await getLearningList(obj)

      if (list.length < this.pageParm.pageSize) {
        this.hasMore = false
      }

      if (list.length > 0) {
        this.learningList = this.learningList.concat(list)
        this.pageParm.pageNo++
      }

      this.pageParm.total = Number(total)
      this.loading = false
    },
    initPage() {
      // 初始化页面
      this.learningList = []
      this.pageParm.pageNo = 1
      this.pageParm.pageSize = 10
      this.pageParm.total = 0
      this.loading = false
      this.hasMore = true
    },
    async clickSubject(item) {
      // 切换科目、资料分类、查阅情况时暂停音频播放
      for (let key in this.audioContexts) {
        const { context, item } = this.audioContexts[key]
        context.context.pause()
        context.status = false
        context.$emit('on-click', { readStatus: 2, item: item })
      }

      //点击tab切换时
      this.initPage()
      if (item.dictType == 'subject') {
        this.subjectId = item.value

        // 上传模块使用时间
        this.$store.state.moduleUse.currentModuleUse.submit()
        // 重置
        this.$store.state.moduleUse.currentModuleUse.onSubjectChange(this.subjectId)
      } else if (item.dictType == 'data_file_type') {
        this.folderTypeId = item.value
      } else {
        this.readStatusId = item.value
      }
      await this.getData({
        fileType: this.folderTypeId == '0' ? '' : this.folderTypeId,
        readStatus: this.readStatusId == '-1' ? '' : this.readStatusId,
        subject: this.subjectId,
        fileName: this.fileName ? this.fileName : undefined,
        ...this.pageParm
      })
    },
    onPlay(e, i) {
      //视频全屏播放，退出全部播放停止
      if (e.isFull) {
        setReadStatus(e.item.id, 1, new Date())
      } else {
        setReadStatus(e.item.id, 2, new Date())
        e.item.readStatus = 1
      }
    },
    onPlayAudio(data) {
      const { id } = data

      for (let key in this.audioContexts) {
        if (key != id) {
          const { context } = this.audioContexts[key]
          context.context.pause()
          context.status = false
        }
      }

      this.audioContexts[id] = data
    },
    loadMore() {
      this.getData({
        fileType: this.folderTypeId == '0' ? '' : this.folderTypeId,
        readStatus: this.readStatusId == '-1' ? '' : this.readStatusId,
        subject: this.subjectId,
        ...this.pageParm
      })
    },
    search() {
      this.initPage()
      this.getData({
        fileType: this.folderTypeId == '0' ? '' : this.folderTypeId,
        readStatus: this.readStatusId == '-1' ? '' : this.readStatusId,
        subject: this.subjectId,
        fileName: this.fileName ? this.fileName : undefined,
        ...this.pageParm
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  border-radius: 16px;

  .learning-list {
    &:not(:first-child) {
      margin-top: 40px;
    }
  }
}

.grid {
  display: inline-grid;
  grid-template-columns: 285px 285px 285px 285px;
  grid-column-gap: 19px;
  grid-row-gap: 19px;
}

::v-deep .el-input--medium .el-input__inner {
  height: 35px;
}
</style>
